using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using UnityEngine;
using UnityEditor;
using Debug = UnityEngine.Debug; 
namespace UnityEditor
{
public class CSharp2LuaEditor : EditorWindow
{
	private string compilerPath = null;
	private string srcPath,destPath;
	private bool iscompilerexe = false;
	private bool isCompileToggle = false;
	public CSharp2LuaEditor()
	{
	}
	[MenuItem("XLua/CSharp2Lua")]
	static void Show()
	{
		var scene = EditorWindow.GetWindow<SceneView>("Scene", false);//.GetWindow(typeof(SceneView));// SceneView.currentDrawingSceneView;
		var window = (CSharp2LuaEditor)GetWindow(typeof(CSharp2LuaEditor), false, "CSharp2LuaEditor");

		if (scene)
		{
			window.position = new Rect(scene.position.xMin + 100f, scene.position.yMin + 100f, 900f, 600);
		}
		else
		{
			window.position = new Rect(Screen.width/2,Screen.height/2, 400f, 300f);
		}
			window.minSize = new Vector2(648, 300f);
		string path = EditorPrefs.GetString("CSharp2Lua");
		if (!string.IsNullOrEmpty(path))
		{
			window.compilerPath = path.ToString();
			window.iscompilerexe = path.EndsWith(".exe");
		}
		path = EditorPrefs.GetString("SrcCSharp2Lua");
		if (!string.IsNullOrEmpty(path))
		{
			window.srcPath = path.ToString();
		}
		path = EditorPrefs.GetString("DestCSharp2Lua");
		if (!string.IsNullOrEmpty(path))
		{
			window.destPath = path.ToString();
		}
		window.OnResized();
	}
	private void Awake()
	{
	}

	void OnResized()
	{
		float width = this.position.width;
		float height = this.position.height;
		
		posSrc = new Rect(50,30,width-100,30);
		posDesc =new Rect(50,70,width-100,30);
		posexe = new Rect(50,110,width-100,30);
		posCompile = new Rect((width - 100) / 2,200,100,30);
		posSave = new Rect((width - 100) / 2,250,100,30);
		
		posSelSrc = new Rect(posSrc.x + posSrc.width+ select.x,posSrc.y,30,20);
		posSeldes = new Rect(posDesc.x +posDesc.width+ select.x,posDesc.y,30,20);
		posSelexe = new Rect(posexe.x+posexe.width + select.x,posexe.y,30,20);
		posCompileToggle = new Rect(posCompile.x + posCompile.width + 20,posCompile.y,100,30);
	}

	Rect posSrc = new Rect(0,0,200,50);
	Rect posDesc = new Rect(0,100,200,50);
	Rect posexe = new Rect(0,200,200,50);
	Rect posCompile = new Rect(0,300,100,50);
	Rect posCompileToggle = new Rect(350,300,100,50);
	Rect posSave = new Rect(0,360,100,50);
	
	
	Rect select = new Rect(5,0,30,20);
	Rect posSelSrc = new Rect(5,0,30,20);
	Rect posSeldes = new Rect(5,0,30,20);
	Rect posSelexe = new Rect(5,0,30,20);
	private void OnGUI()
	{
		EditorGUILayout.BeginVertical();
		if (!isCompileToggle)
		{
			EditorGUILayout.BeginHorizontal();
			/*string src = */
			EditorGUI.LabelField(posSrc, "Src", srcPath);
			/*if (src != srcPath)
			{
				srcPath = src;
			}*/
			if (GUI.Button(new Rect(posSelSrc.x + select.width, posSelSrc.y, select.width, select.height), "..."))
			{
				string news = EditorUtility.OpenFolderPanel("c#目录", srcPath ?? Application.dataPath, "");
				if (!string.IsNullOrEmpty(news))
					srcPath = news;
			}
			EditorGUILayout.EndHorizontal();
		}
		EditorGUILayout.BeginHorizontal();
				/*string dest = */EditorGUI.LabelField(posDesc, "dest", destPath);
				/*if (dest != destPath)
				{
					destPath = dest;
				}*/
				if (GUI.Button(posSeldes, "..."))
				{
					string news = EditorUtility.OpenFolderPanel("lua目录", destPath??Application.dataPath, "");
					if (!string.IsNullOrEmpty(news))
						destPath = news;
				}
			EditorGUILayout.EndHorizontal();
			EditorGUILayout.BeginHorizontal();
				/*string exe = */EditorGUI.LabelField(posexe, "exe", compilerPath);
				/*if (exe != compilerPath)
				{
					compilerPath = exe;
				}*/
				if (GUI.Button(posSelexe, "..."))
				{
					string c = EditorUtility.OpenFilePanelWithFilters("选择CSharp.Lua", compilerPath??Application.dataPath, new string[]{"*.exe","*.dll"});
					if (!string.IsNullOrEmpty(c))
					{
						iscompilerexe = c.EndsWith(".exe");
						compilerPath = c;
					}
				}
			EditorGUILayout.EndHorizontal();
		//
		EditorGUILayout.BeginHorizontal();
		
		isCompileToggle = GUI.Toggle(posCompileToggle,isCompileToggle,"自选文件");
		if (GUI.Button(posCompile, "compile"))
		{
			Compile();
		}
		EditorGUILayout.EndHorizontal();
		
		if (GUI.Button(posSave, "save Setting"))
		{
			SaveSetting();
		}
		EditorGUILayout.EndVertical();
	}

	void Compile()
	{/*
CSharp.Lua.exe -h
Usage: CSharp.lua [-s srcfolder] [-d dstfolder]
Arguments 
-s              : source directory, all *.cs files whill be compiled
-d              : destination  directory, will put the out lua files

Options
-h              : show the help message    
-l              : libraries referenced, use ';' to separate      
-m              : meta files, like System.xml, use ';' to separate     
-csc            : csc.exe command argumnets, use ';' to separate

-c              : support classic lua version(5.1), default support 5.3 
-i              : indent number, default is 2
-sem            : append semicolon when statement over
-a              : attributes need to export, use ';' to separate, if ""-a"" only, all attributes whill be exported
 */
		if (string.IsNullOrEmpty(compilerPath) || string.IsNullOrEmpty(srcPath)||string.IsNullOrEmpty(destPath))
		{
			return;
		}
		string theFile = null;
		if (isCompileToggle)
		{
			string s = EditorUtility.OpenFilePanel("选择编译文件", destPath, "cs");
			if (string.IsNullOrEmpty(s))
			{
				return;
			}
			theFile = s;
			srcPath = new FileInfo(s).Directory.FullName;
		}
		
		string lisb = string.Join(Path.DirectorySeparatorChar + "", new string[]
		{
			new DirectoryInfo(Application.dataPath).Parent.FullName,
			"Library","PlayerDataCache","Data","Managed"
		});
		string[] dlls = Directory.GetFiles(lisb,"*.dll");
		List<string> skipDll = new List<string>
		{
			"mscorlib.dll",
			"System.dll",
			"System.Core.dll",
			"Microsoft.CSharp.dll"
		};
		List<string> tmp = new List<string>();
		foreach (var v in dlls)
		{
			bool isSkip = false;
			foreach (var skip in skipDll)
			{
				if (v.EndsWith(skip))
				{
					isSkip = true;
					break;
				}
			}
			if(!isSkip)
				tmp.Add(v);
		}
		dlls = tmp.ToArray();
		ProcessStartInfo ps = new ProcessStartInfo();
		ps.CreateNoWindow = true; 
		string cmds = "";
		if (iscompilerexe)
		{
			ps.FileName = compilerPath;
			cmds += string.Join(" ", new string[]
			{
				"-s", srcPath, "-d", destPath,"-l","\""+string.Join("\";\"",dlls)+"\""
			});
		}
		else
		{
			ps.FileName = "dotnet";
			cmds += string.Join(" ", new string[]
			{
				compilerPath,"-s", srcPath, "-d", destPath,"-l","\""+string.Join("\";\"",dlls)+"\""
			});
		}
		if (!string.IsNullOrEmpty(theFile))
			cmds += " -f " + theFile;
//		ps.RedirectStandardOutput = true;
//		ps.RedirectStandardError = true;
//		ps.UseShellExecute = false;
		ps.WorkingDirectory = Application.dataPath;
		ps.Arguments = cmds;
		Process p = Process.Start(ps);
//		p.OutputDataReceived -= ReceiveOutput;
//		p.OutputDataReceived += ReceiveOutput; 
		Debug.Log(ps.FileName +" "+ cmds);
	}
	void SaveSetting()
	{
		
		if (!string.IsNullOrEmpty(compilerPath))
		{
			EditorPrefs.SetString("CSharp2Lua",compilerPath);
		} 
		if (!string.IsNullOrEmpty(srcPath))
		{
			EditorPrefs.SetString("SrcCSharp2Lua",srcPath); 
		}
		if (!string.IsNullOrEmpty(destPath))
		{
			EditorPrefs.SetString("DestCSharp2Lua",destPath);
		}
	}

	void ReceiveOutput(object sender, DataReceivedEventArgs e)
	{
		UnityEngine.Debug.Log(e.Data);
	}
}



}